package com.itheima.mall.service.omsService;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.PageResult;
import com.itheima.mall.service.omsService.OmsOrderApi;
import com.itheima.dto.OrderDto;
import com.itheima.mall.mapper.omsMapper.OmsOrderItemMapper;
import com.itheima.mall.mapper.omsMapper.OmsOrderMapper;
import com.itheima.mall.mapper.omsMapper.OmsOrderOperateHistoryMapper;
import com.itheima.pojo.oms.OmsOrder;
import com.itheima.pojo.oms.OmsOrderItem;
import com.itheima.pojo.oms.OmsOrderOperateHistory;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@DubboService
public class OmsOrderApiImpl implements OmsOrderApi {
    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private OmsOrderOperateHistoryMapper omsOrderOperateHistoryMapper;
    @Autowired
    private OmsOrderItemMapper omsOrderItemMapper;
    //分页
    @Override
    public PageResult<OmsOrder> page(OrderDto orderDto, Integer pageNum, Integer pageSize) {
        Page<OmsOrder> page = new Page<>(pageNum,pageSize);
        //构建条件构造器
        LambdaQueryWrapper<OmsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(orderDto.getCreateTime()),OmsOrder::getCreateTime,orderDto.getCreateTime());
        queryWrapper.eq(OmsOrder::getDeleteStatus,0);
        queryWrapper.eq(StrUtil.isNotBlank(orderDto.getOrderSn()),OmsOrder::getOrderSn,orderDto.getOrderSn());
        queryWrapper.eq(ObjectUtil.isNotEmpty(orderDto.getOrderType()),OmsOrder::getOrderType,orderDto.getOrderType());
        queryWrapper.eq(ObjectUtil.isNotEmpty(orderDto.getSourceType()),OmsOrder::getSourceType,orderDto.getSourceType());
        queryWrapper.eq(ObjectUtil.isNotEmpty(orderDto.getStatus()),OmsOrder::getStatus,orderDto.getStatus());
        //收货人姓名/号码  receiverKeyword
        queryWrapper.like(ObjectUtil.isNotEmpty(orderDto.getReceiverKeyword()),OmsOrder::getBillReceiverPhone,orderDto.getReceiverKeyword())
                .or().like(ObjectUtil.isNotEmpty(orderDto.getReceiverKeyword()),OmsOrder::getReceiverName,orderDto.getReceiverKeyword());
       omsOrderMapper.selectPage(page,queryWrapper);
       PageResult<OmsOrder> pageResult = new PageResult<>();
       pageResult.setPageNum(pageNum);
       pageResult.setPageSize(pageSize);
       pageResult.setTotalPage((int)page.getPages());
       pageResult.setTotal((int)page.getTotal());
       pageResult.setItems(page.getRecords());

        return pageResult;
    }

    @Override
    public void deleteByIds(Integer[] ids) {
      LambdaQueryWrapper<OmsOrder> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.in(ids !=null,OmsOrder::getId,ids);
      //判断选择的订单中是否有未关闭的订单
        List<OmsOrder> omsOrders = omsOrderMapper.selectList(queryWrapper);
        for (OmsOrder omsOrder : omsOrders) {
            if(omsOrder.getStatus()<4){
                throw new RuntimeException("有订单还未关闭");
            }
        }
        LambdaUpdateWrapper<OmsOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(OmsOrder::getId,ids).eq(OmsOrder::getStatus,4)
                .set(OmsOrder::getDeleteStatus, 1);

        omsOrderMapper.update(null,queryWrapper);

    }

    @Override
    public void close(Integer[] ids, String note) {
        //修改
        LambdaUpdateWrapper<OmsOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(ids!=null,OmsOrder::getId,ids).set(OmsOrder::getStatus,4);
        omsOrderMapper.update(null,wrapper);
        //添加操作记录
        for (Integer id : ids) {
            OmsOrderOperateHistory omsOrderOperateHistory = new OmsOrderOperateHistory();
            omsOrderOperateHistory.setOrderId(id.longValue());
            omsOrderOperateHistory.setOperateMan("后台管理员");
            omsOrderOperateHistory.setCreateTime(DateTime.now());
            omsOrderOperateHistory.setOrderStatus(4);
            omsOrderOperateHistory.setNote(note);
            omsOrderOperateHistoryMapper.insert(omsOrderOperateHistory);
        }

    }

    @Override
    public void delivery(List<Map<String, String>> list) {

        for (Map<String, String> map : list) {
            LambdaUpdateWrapper<OmsOrder> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(OmsOrder::getId,map.get("orderId"))
                    .set(OmsOrder::getDeliveryCompany,map.get("deliveryCompany"))
                    .set(OmsOrder::getDeliverySn,map.get("deliverySn"));
            omsOrderMapper.update(null,wrapper);
          //添加操作记录
            OmsOrderOperateHistory omsOrderOperateHistory = new OmsOrderOperateHistory();
            omsOrderOperateHistory.setOrderId(Long.valueOf(map.get("orderId")));
            omsOrderOperateHistory.setOperateMan("后台管理员");
            omsOrderOperateHistory.setCreateTime(DateTime.now());
            omsOrderOperateHistory.setOrderStatus(2);
            omsOrderOperateHistory.setNote("完成发货");
            omsOrderOperateHistoryMapper.insert(omsOrderOperateHistory);
        }
    }

    @Override
    public OmsOrder findById(Integer id) {
        OmsOrder omsOrder = omsOrderMapper.selectById(id);
        return omsOrder;
    }

    @Override
    public List<OmsOrderItem> findItems(Integer id) {
       LambdaQueryWrapper<OmsOrderItem> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.eq(OmsOrderItem::getOrderId, id);
        List<OmsOrderItem> omsOrderItems = omsOrderItemMapper.selectList(queryWrapper);
        return omsOrderItems;

    }

    @Override
    public void updateMoney(Double discountAmount, Double freightAmount, Integer orderId, Integer status) {

        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setId(orderId.longValue());
        omsOrder.setDiscountAmount(new BigDecimal(discountAmount) );
        omsOrder.setFreightAmount(new BigDecimal(freightAmount));
        omsOrder.setStatus(status);
        omsOrderMapper.updateById(omsOrder);
    }

    @Override
    public void updateNote(Long id, String note, Integer status) {
        OmsOrderOperateHistory h = new OmsOrderOperateHistory();
        h.setOrderId(id);
        h.setNote(note);
        h.setOrderStatus(status);
        h.setCreateTime(DateTime.now());
        h.setOperateMan("后台管理员");
        omsOrderOperateHistoryMapper.insert(h);
    }

    @Override
    public void updateReceiver(Map<String, String> map) {
        //修改订单信息
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setReceiverCity(map.get("crceiverCity"));
        omsOrder.setReceiverDetailAddress(map.get("receiverDetailAddress"));
        omsOrder.setReceiverName(map.get("receiverName"));
        omsOrder.setReceiverPhone(map.get("receiverPhone"));
        omsOrder.setReceiverPostCode(map.get("receiverPostCode"));
        omsOrder.setReceiverProvince(map.get("receiverProvince"));
        omsOrder.setReceiverRegion(map.get("receiverRegion"));
        omsOrder.setStatus(Integer.valueOf(map.get("status")));

        omsOrderMapper.updateById(omsOrder);

        //添加记录
        OmsOrderOperateHistory history = omsOrderOperateHistoryMapper.selectById(map.get("orderId"));
        history.setOrderId(Convert.toLong(map.get("orderId")));
        history.setOrderStatus(0);
        history.setCreateTime(DateTime.now());
        history.setNote("修改收货人信息");
        history.setOperateMan("后台管理员");

        omsOrderOperateHistoryMapper.insert(history);
    }
}
